<?php
class admin_users extends main{   
    
    public function __construct(){}
    
    //Hooks
    protected static function hookLogin(){
        
        //On vérifie tout de suite la présence de cookies valide
        if($_COOKIE['adm_r'] == "1"){
            $c_uniqueid = $_COOKIE['adm_s'];
            $c_login = self::decrypt($_COOKIE['adm_l'],$c_uniqueid);
            $c_passwd = self::decrypt($_COOKIE['adm_p'],$c_uniqueid);
            $c_remember = $_COOKIE['adm_r'];
            
            //On verifie le salt
            $sql = "SELECT au.*, ag.groupname
                    FROM ".parent::getConfig('db_prefix')."admin_users AS au
                    INNER JOIN ".parent::getConfig('db_prefix')."admin_groups AS ag
                    ON ag.id = au.groupid
                    WHERE au.login = '".$login."'
                    AND au.password = '".$passwd."'
                    AND au.salt = '".$uniqueid."'";
            $result = dao::request_assoc($sql);
            if($result){
                unset($c_login,$c_passwd,$c_remember,$c_uniqueid);
                self::setLogin($result[0],true);
            }else{
                unset($c_login,$c_passwd,$c_remember,$c_uniqueid);
                @setcookie('adm_r', "0", time() + 60, null, null, false, true);
                @setcookie('adm_s', "", time() + 60, null, null, false, true);
                @setcookie('adm_l', "", time() + 60, null, null, false, true);
                @setcookie('adm_p', "", time() + 60, null, null, false, true);
                
                $login = parent::getPost('adm_login');
                $passwd = md5(parent::getPost('adm_passwd'));
                $remember = parent::getPost('adm_remember_connection');
                ($remember) ? $cookie = true : $cookie = false;
                
                //On cherche les infos
                if($login && $passwd){
                    $sql = "SELECT au.*, ag.groupname
                            FROM ".parent::getConfig('db_prefix')."admin_users AS au
                            INNER JOIN ".parent::getConfig('db_prefix')."admin_groups AS ag
                            ON ag.id = au.groupid
                            WHERE au.login = '".$login."'
                            AND au.password = '".$passwd."'";
                    $result = dao::request_assoc($sql);
                    if(count($result) == 0){
                        return str_replace('%1%',parent::getConfig('site_url'),lang::show("Incorrect_login_or_password"));
                    }else{
                        if($result[0]['status'] == 0){
                            return str_replace('%1%',parent::getConfig('site_url'),lang::show("Account_disabled"));
                        }else{
                            self::setLogin($result[0],$cookie);
                        }
                    }
                }
            }
        }else{//sinon on prend le postvars
            $login = parent::getPost('adm_login');
            $passwd = md5(parent::getPost('adm_passwd'));
            $remember = parent::getPost('adm_remember_connection');
            ($remember) ? $cookie = true : $cookie = false;
            
            //On cherche les infos
            if($login && $passwd){
                $sql = "SELECT au.*, ag.groupname
                        FROM ".parent::getConfig('db_prefix')."admin_users AS au
                        INNER JOIN ".parent::getConfig('db_prefix')."admin_groups AS ag
                        ON ag.id = au.groupid
                        WHERE au.login = '".$login."'
                        AND au.password = '".$passwd."'";
                $result = dao::request_assoc($sql);
                if(count($result) == 0){
                    return str_replace('%1%',parent::getConfig('site_url'),lang::show("Incorrect_login_or_password"));
                }else{
                    if($result[0]['status'] == 0){
                        return str_replace('%1%',parent::getConfig('site_url'),lang::show("Account_disabled"));
                    }else{
                        self::setLogin($result[0],$cookie);
                    }
                }
            }
        }
    }
    
    protected static function disconnect(){
        @setcookie('adm_r', "0", time() + 60, null, null, false, true);
        @setcookie('adm_s', "", time() + 60, null, null, false, true);
        @setcookie('adm_l', "", time() + 60, null, null, false, true);
        @setcookie('adm_p', "", time() + 60, null, null, false, true);
        
        session_destroy();
    }
    
    //Tags
    protected static function getLoginTags(){
        //On defini les tags de bases
        $tags['page_title'] = lang::show('Login');        
        return $tags;
    }
    
    protected static function getMenuAccount(){
        //On envois le menu du compte en cours
        $html = '';
        
        $html .= '<div id="account_avatar"><img src="'.main::getConfig('site_url').'system/img/users/'.$_SESSION['admin']['user']['avatar'].'"/></div>';
        $html .= '<div id="account_infos">';
        $html .= '  <span class="account_owner">'.$_SESSION['admin']['user']['firstname'].' '.$_SESSION['admin']['user']['lastname'].'</span>';
        $html .= '  <span class="account_group">'.$_SESSION['admin']['user']['groupname'].'</span>';
        $html .= '  <span class="account_email">'.$_SESSION['admin']['user']['email'].'</span>';
        $html .= '  <span class="account_lastconnexion">'.lang::show('Last connection').' : '.date("d/m/Y H:i:s",$_SESSION['admin']['user']['last_connection']).'</span>';
        $html .= '</div>';
        
        return $html;
    }
    
    
    protected static function getMenuOptions(){
        //On envois le menu du compte en cours
        $html = '';
        
        $html .= '<input type="button" class="btn_account options_menu" onclick="javascript:admin_account();" value="'.lang::show('Account').'"/> ';
        $html .= '<input type="button" class="btn_support options_menu" onclick="javascript:admin_support();" value="'.lang::show('Support').'"/> ';
        $html .= '<br/>';
        $html .= '<input type="button" class="btn_logout options_menu" onclick="javascript:admin_disconnect();" value="'.lang::show('Disconnect').'"/> ';
        $html .= '<input type="button" class="btn_langs options_menu" onclick="javascript:admin_langs();" value="'.lang::show('Langs').'"/> ';
        
        
        return $html;
    }
    
    // PRIVATE functions
    
    //Set info Login into SESSION/COOKIE
    private static function setLogin($data,$cookie = false){
        if($cookie){
            $new_uniqueid = common::GenCode(20);
            
            //On set les cookies
            @setcookie('adm_r', "1", time() + 365*24*3600, null, null, false, true);
            @setcookie('adm_s', $new_uniqueid, time() + 365*24*3600, null, null, false, true);
            @setcookie('adm_l', self::encrypt($data['login'],$new_uniqueid), time() + 365*24*3600, null, null, false, true);
            @setcookie('adm_p', self::encrypt($data['passwd'],$new_uniqueid), time() + 365*24*3600, null, null, false, true);
            
            //on met a jour le salt/date derniere connection
            $sql = "UPDATE ".parent::getConfig('db_prefix')."admin_users
                    SET salt = '".$new_uniqueid."', last_connection = ".time()."
                    WHERE id = ".$data['id'];
            dao::exec_request($sql);
        }else{
            //on met a jour la date derniere connection
            $sql = "UPDATE ".parent::getConfig('db_prefix')."admin_users
                    SET last_connection = ".time()."
                    WHERE id = ".$data['id'];
            dao::exec_request($sql);
        }
        
        $_SESSION['admin_auth'] = true;
        $_SESSION['admin']['user'] = $data;
        $_SESSION['admin']['current_page'] = "desktop";
        
        if($data['default_lang'] != lang::getDefaultLang()){
            lang::changeLang($data['default_lang']);
        }
        
        
        //RIGHT
        $sql = "SELECT r.domain, r.right
                FROM ".parent::getConfig('db_prefix')."admin_rights AS r
                INNER JOIN ".parent::getConfig('db_prefix')."admin_groupsrights AS gr
                ON gr.rightid = r.id
                WHERE gr.groupid = ".$data['groupid'];
        $result = dao::request_assoc($sql);
        if($result){
            $_SESSION['admin']['right'] = array();
            $_SESSION['admin']['right']['global'] = array();
            $_SESSION['admin']['right']['modules'] = array();
            foreach($result as $right){
                $_SESSION['admin']['right'][$right['domain']][$right['right']] = true;
            }
        }
        
        header('location: /'.main::getConfig('admin_path').'/desktop.html');
        die();
    }
    
    //ENCRYPT/DECRYPT Functions for COOKIE VERIFICATIONS ONLY
    private static function encrypt($text,$salt){
        return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
    }
    
    private static function decrypt($text,$salt){ 
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
    }
    
}
?>